<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/28
 * Time: 16:38
 */

namespace app\applet\model;


use think\Config;
use think\Db;
use think\Exception;

class SupplyChain
{
    public function getUserMoney()
    {
        $id = get_header_id("token");
        $data = Db::name("member_asset a")
            ->join("mm_member m","m.member_id = a.member_id")
            ->field("m.nickName,a.score,a.coin")
            ->where(['a.member_id'=>$id])
            ->find();
        return $data;

    }
    public function brandName()
    {
        $data = Db::name("choice_goods")
            ->Distinct(true)
            ->field("brand_name")
            ->select();
        foreach ($data as $k=>$v)
        {
            $count = Db::name("choice_brand")
                ->field("id")
                ->where(["brand_name"=>trim($v['brand_name'])])
                ->find();
            if($count)
            {
                $insert['brand_name'] = trim($v['brand_name']);
                $insert['update_time'] = time();
                Db::name("choice_brand")
                    ->where(['id'=>$count['id']])
                    ->update($insert);
            }else{
                $insert['brand_name'] = trim($v['brand_name']);
                $insert['create_time'] = time();
                Db::name("choice_brand")->insert($insert);
            }
        }
    }
    public function brandList()
    {
        $data = Db::name("choice_brand")
            ->field("id,brand_name")
            ->order(['id'=>'desc'])
            ->select();
        return $data;
    }
    public function hotShopList($current_page,$page_num,$where,$order)
    {
        $where_new['status'] = 1;
        $where_new['supply_delete_status'] = 1;
        $where_new['shop_status'] = 1;
        $where_new['shop_delete_status'] = 1;

        $data = Db::name("choice_goods")
            ->field("id,goods_id,cover,title,market_price,agreement_price,sale")
            ->where($where)
            ->where($where_new)
            ->order($order)
            ->page($current_page,$page_num)
            ->select();
        foreach ($data as $k=>$v)
        {
            $data[$k]['market_price'] = sprintf("%.2f",$v['market_price'] / 100);
            $data[$k]['agreement_price'] = sprintf("%.2f",$v['agreement_price'] * getReturnPop($v['goods_id'],2) / 100);
            $data[$k]['back_gold_coin'] = sprintf("%.1f",$v['agreement_price'] * getReturnPop($v['goods_id'],2) * 2 / 100);
        }
        $total_num = Db::name("choice_goods")
            ->where($where)
            ->where($where_new)
            ->count();
        $list['current_page'] = $current_page;
        $list['total_page'] = ceil($total_num / $page_num);
        $list['page_num'] = $page_num;
        $list['total_num'] = $total_num;
        $list['data'] = $data;
        return $list;
    }
    public function rebateShopList($current_page,$page_num,$where,$order)
    {
        $where_new['status'] = 1;
        $where_new['supply_delete_status'] = 1;
        $where_new['shop_status'] = 1;
        $where_new['shop_delete_status'] = 1;

        $data = Db::name("choice_goods")
            ->field("id,goods_id,cover,title,market_price,agreement_price,sale")
            ->where($where)
            ->where($where_new)
            ->order($order)
            ->page($current_page,$page_num)
            ->select();
        foreach ($data as $k=>$v)
        {
            $data[$k]['market_price'] = sprintf("%.2f",$v['market_price'] / 100);
            $data[$k]['agreement_price'] = sprintf("%.2f",$v['agreement_price'] * getReturnPop($v['goods_id'],1) / 100);
            $data[$k]['back_buy_integral'] = sprintf("%.1f",$v['agreement_price'] * 0.2 / 100);
            $data[$k]['back_gold_coin'] = sprintf("%.1f",$v['agreement_price'] * Config::get("gold_coin_config") / 100);
        }
        $total_num = Db::name("choice_goods")
            ->where($where)
            ->where($where_new)
            ->count();
        $list['current_page'] = $current_page;
        $list['total_page'] = ceil($total_num / $page_num);
        $list['page_num'] = $page_num;
        $list['total_num'] = $total_num;
        $list['data'] = $data;
        return $list;
    }
    public function cateList($current_page,$page_num,$parent_id)
    {
        $data = Db::name("choice_cate")
            ->field("id,name,parent_id,url")
            ->where(['parent_id'=>$parent_id])
            ->order(['sort'=>'desc'])
            ->page($current_page,$page_num)
            ->select();
        $total_num = Db::name("choice_cate")
            ->where(['parent_id'=>$parent_id])
            ->count();
        $list['current_page'] = $current_page;
        $list['total_page'] = ceil($total_num / $page_num);
        $list['page_num'] = $page_num;
        $list['total_num'] = $total_num;
        $list['data'] = $data;
        return $list;
    }

    /**
     * 商家已发货
     */
    public function delivery($order_sn,$spec_id){
        $orderInfo=Db::name("order")->where(['order_sn'=>$order_sn])->field("order_id,source_type")->find();
        $order_id=$orderInfo['order_id'];
        $source_type=$orderInfo['source_type'];
        if(in_array($source_type,[2,3])){
            Db::startTrans();
            try{
                $num=Db::name("order_goods")->where(['order_id'=>$order_id,'spec_id'=>$spec_id])->update(['og_d_status'=>2]);
                if($num<=0){
                    throw  new Exception("更新失败");
                }
                $count=Db::name("order_goods")->where(['order_id'=>$order_id,'og_d_status'=>['in',[0,1]]])->count();
                if($count>0){
                    $num=Db::name('order')->where(['order_id'=>$order_id])
                        ->update(['order_status'=>11]);
                }else{
                    $num=Db::name('order')->where(['order_id'=>$order_id])
                        ->update(['order_status'=>3]);
                }
                if($num<=0){
                    throw  new Exception("更新失败");
                }
                Db::commit();
                return true;
            }catch (Exception $e){
                Db::rollback();
                return false;
            }
        }else{
            return false;
        }
    }

    /*
     * 交易完成
     */
    public function completeOrder($order_sn,$spec_id){
        $orderInfo=Db::name("order")->where(['order_sn'=>$order_sn])->field("order_id,source_type,member_id")->find();
        $order_id=$orderInfo['order_id'];
        $source_type=$orderInfo['source_type'];
        $member_id=$orderInfo['member_id'];
        if(in_array($source_type,[2,3])){
            Db::startTrans();
            try{
                $num=Db::name("order_goods")->where(['order_id'=>$order_id,'spec_id'=>$spec_id])->update(['is_complete'=>1]);
                if($num<=0){
                    throw  new Exception("更新失败");
                }
                $count=Db::name("order_goods")->where(['order_id'=>$order_id,'is_complete'=>0])->count();
                if($count>0){
                    $num=Db::name('order')->where(['order_id'=>$order_id])
                        ->update(['order_status'=>4]);
                    if($num<=0){
                        throw  new Exception("更新失败");
                    }
                    $tm=time();
                    $og_id=Db::name("order_goods")->where(['order_id'=>$order_id,'spec_id'=>$spec_id])->value("og_id");
                    $logList=Db::name("member_asset_log")->where(['type'=>3,"relation_id"=>$order_id,'relation_sid'=>$og_id,'log_type_id'=>['in',[47,58]]])->select();
                    if(!empty($logList)){
                        foreach ($logList as $log){
                            $logMember=$log['member_id'];
                            $amount=$log['amount'];
                            $change_type=$log['change_type'];
                            if($log['log_type_id']==47){
                                if( $change_type==1){
                                    $score_money= $amount;
                                    $coin_money= 0;
                                    $description="商城消费返利奖";
                                    $log_type_id="73";
                                }
                            }elseif($log['log_type_id']==58){
                                if( $change_type==1){
                                    $score_money= $amount;
                                    $coin_money= 0;
                                    $description="商城消费推荐奖";
                                    $log_type_id="5";
                                }elseif($change_type==2){
                                    $description="商城消费推荐奖";
                                    $log_type_id=72;
                                    $score_money= 0;
                                    $coin_money= $amount;
                                }
                            }
                            $asset_log[] = ['member_id' => $logMember, 'type' => 1, 'amount' =>  $amount,
                                'source_type' => 2, 'description' =>$description, "change_type" => $change_type, 'log_type_id' =>$log_type_id,
                                'relation_id' => $order_id,'relation_sid'=>$og_id, 'create_time' => $tm, 'update_time' => $tm,'release_status'=>2];

                            $num=Db::query("update mm_member_asset set frozen_score=frozen_score+$coin_money,seven_frozen_score=seven_frozen_score-$score_money,frozen_coin=frozen_coin+$coin_money,seven_frozen_coin=seven_frozen_coin-$coin_money where member_id=".$logMember." and seven_frozen_score>=".$score_money." and seven_frozen_coin>=".$coin_money);
                            if($num<=0){
                                throw new Exception("更新失败");
                            }
                        }
                        $num=Db::name("member_asset_log")->where(['type'=>3,"relation_id"=>$order_id,'relation_sid'=>$og_id,'log_type_id'=>[47,58]])->delete();
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                        $num=Db::name("member_asset_log")->insertAll($asset_log);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                        $num=Db::name("order_goods")->where(['og_id'=>$og_id])->update(['give_status'=>4]);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                    }
                }
                $orderStatus=Db::name("order")->where(['order_id'=>$order_id])->value("status");
                $goodsList=Db::name("order_goods")->where(['order_id'=>$order_id])->field("og_d_status")->select();
                $isComplete=true;
                foreach ($goodsList as $ogoods){
                    if(!in_array($ogoods['og_d_status'],[3,4])||!in_array( $orderStatus,[4,5])){//未收货 未评价
                        $isComplete=false;
                    }
                }
                //订单交易完成
                if($isComplete){
                    $num=Db::name("order")->where(['order_id'=> $order_id])->update(['status'=>12]);
                    if($num<=0){
                        throw new Exception("更新失败");
                    }
                }
                Db::commit();
                return true;
            }catch (Exception $e){
                Db::rollback();
                return false;
            }
        }else{
            return false;
        }
    }

}